package socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ChatServer {

	private List clientList = new ArrayList();
	private ServerSocket server;
	private int sum = 0;

	public static void main(String[] args) {
		ChatServer server = new ChatServer();
		server.start();
	}

	public void start() {
		try {
			server = new ServerSocket(5678);
			System.out.println("-----服务器已启动 。。。");
			while (true) {
				Socket client = server.accept();
				sum++;
				String cid = "C" + sum;
				ClientThread clientThread = new ClientThread(client, cid);
				new Thread(clientThread).start();
				clientList.add(clientThread);
				System.out.println("-----新的用户(" + cid + ")接入 。。。");
				System.out.println("-----当前总用户数(" + clientList.size() + ")");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				server.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private class ClientThread implements Runnable {

		private BufferedReader in;
		private PrintWriter out;
		private String cid;

		public ClientThread(Socket socket, String cid) {
			try {
				in = new BufferedReader(new InputStreamReader(
						socket.getInputStream()));
				out = new PrintWriter(new OutputStreamWriter(
						socket.getOutputStream()));
				this.cid = cid;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		public void run() {
			try {
				out.println("-----当前用户(" + cid + ")");
				out.flush();
				while (true) {
					String msg = in.readLine();
					System.out.println("<" + cid + "> " + msg);
					for (int i = 0; i < clientList.size(); i++) {
						ClientThread client = (ClientThread) clientList.get(i);
						client.send(cid, msg);
					}
				}
			} catch (IOException e) {
				clientList.remove(this);
				System.out.println("-----用户(" + cid + ")退出！");
				System.out.println("-----当前总用户数(" + clientList.size() + ")");
			} finally {
				try {
					in.close();
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		private void send(String cid, String msg) {
			out.println("<" + cid + "> " + new Date().toLocaleString() + "  "
					+ msg);
			out.flush();
		}
	}

}
